package com.digitalchina.lxnsy.activity.management;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.URL;
import com.digitalchina.lxnsy.entity.LandVO;
import com.digitalchina.lxnsy.entity.OrganizationVO2;
import com.digitalchina.lxnsy.entity.PlantVO;
import com.digitalchina.lxnsy.interfaces.ICallBackPos;
import com.digitalchina.lxnsy.interfaces.IMyNhbPos;
import com.digitalchina.lxnsy.toolkit.CustomDialog;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.OkHttpUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.viewholder.BasicInfoLandHolder;
import com.digitalchina.lxnsy.viewholder.BasicInfoPlantHolder;
import com.digitalchina.lxnsy.widget.EditTextWithClear;
import com.digitalchina.lxnsy.xml.AdminXML;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.lzy.okhttputils.model.HttpParams;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity.management
 * 创建人：郑皓
 * 创建时间：2019/4/23 19:02
 * 修改备注：
 * ================================================
 */
public class BasicInfoActivity extends BaseActivity implements ICallBackPos, IMyNhbPos {

    @Bind(R.id.et_name)
    EditTextWithClear etName;
    @Bind(R.id.et_code)
    EditTextWithClear etCode;
    @Bind(R.id.et_user)
    EditTextWithClear etUser;
    @Bind(R.id.et_tel)
    EditTextWithClear etTel;
    @Bind(R.id.recycler_dk)
    RecyclerView recyclerDk;
    @Bind(R.id.recycler_zh)
    RecyclerView recyclerZh;

    private RecyclerArrayAdapter adapterDk, adapterZh;
    private static final int CODE_DK = 30;
    private static final int CODE_ZH = 31;

    private String enterpriseName = ""; // 企业名称
    private String contactName = ""; // 联系人姓名
    private String socialCreditCode = ""; // 统一社会信用代码
    private String mobilePhone = ""; //联系人电话号码

    private int delPos = -1;

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_basic_info);
        setTitle("基础信息");
    }

    @Override
    public void initMember() {


        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        recyclerDk.setLayoutManager(gridLayoutManager);

        recyclerDk.setAdapter(adapterDk = new RecyclerArrayAdapter(this) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new BasicInfoLandHolder(parent, BasicInfoActivity.this);
            }
        });


        recyclerZh.setLayoutManager(new LinearLayoutManager(this));

        //recyclerZh.addItemDecoration(Utils.setSpaceDecoration(this, false, true, false));

        recyclerZh.setAdapter(adapterZh = new RecyclerArrayAdapter(this) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new BasicInfoPlantHolder(parent, BasicInfoActivity.this);
            }
        });


        getEnterpriseInfo();
    }

    @Override
    public void addListener() {

        adapterDk.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                LandVO vo = (LandVO) adapterDk.getAllData().get(position);
                vo.setIndex(position);
                GotoUtil.gotoForResultActivity(activity, AddLandActivity.class, CODE_DK, "LandVO", vo);
            }
        });


    }

    @Override
    public void setHandler() {
        mHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                switch (message.what) {
                    case MSG_S_0:
                        callBack(message.obj);
                        break;
                    case MSG_F_0:
                        showToast(message.obj.toString());
                        break;
                    case MSG_S_1:// 保存
                        CustomDialog.nativeDialogFinish(activity, "保存成功");
                        break;
                    case MSG_F_1:
                        showToast(message.obj.toString());
                        break;
                    case MSG_S_2:// 删除地块
                        adapterDk.remove(delPos);
                        adapterDk.notifyDataSetChanged();
                        break;
                    case MSG_F_2:
                        showToast(message.obj.toString());
                        break;
                    case MSG_S_3:// 删除种植
                        adapterZh.remove(delPos);
                        break;
                    case MSG_F_3:
                        showToast(message.obj.toString());
                        break;
                }
                return false;
            }
        });
    }

    @Override
    public void callBack(Object object) {

        OrganizationVO2 org = FastJsonUtil.getBean(object.toString(), "organization", OrganizationVO2.class);
        List<LandVO> landList = FastJsonUtil.getListBean(object.toString(), "landParcelInfoList", LandVO.class);
        List<PlantVO> plantList = FastJsonUtil.getListBean(object.toString(), "plantInfoList", PlantVO.class);

        adapterDk.addAll(landList);
        adapterZh.addAll(plantList);

        if (org != null) {
            etName.setText(org.getName());
            etCode.setText(org.getSocialCreditCode());
            etUser.setText(org.getContactName());
            etTel.setText(org.getMobilePhone());
        }

    }

    @Override
    public void rightOnClick() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void clickOk(int pos) {
        delPos = pos;
        LandVO vo = (LandVO) adapterDk.getAllData().get(pos);
        deleteLand(vo.getLandParcelId());

    }

    @OnClick({R.id.layout_dk, R.id.layout_zh, R.id.btn_save})
    public void onViewClicked(View view) {
        hideKeyboard();
        switch (view.getId()) {
            case R.id.layout_dk:
                GotoUtil.gotoForResultActivity(activity, AddLandActivity.class, CODE_DK, "LandVO", new LandVO());
                break;
            case R.id.layout_zh:
                GotoUtil.gotoForResultActivity(activity, AddPlantActivity.class, CODE_ZH, "PlantVO", new PlantVO());
                break;
            case R.id.btn_save:
                saveEnterpriseInfo();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == CODE_DK) { // 地块
                LandVO vo = (LandVO) data.getSerializableExtra("LandVO");
                if (vo.getIndex() > -1) {
                    //修改数据
                    adapterDk.remove(vo.getIndex());
                    adapterDk.insert(vo, vo.getIndex());
                } else {
                    // 新增数据
                    adapterDk.add(vo);
                }
                adapterDk.notifyDataSetChanged();
            } else if (requestCode == CODE_ZH) { // 种植
                PlantVO vo = (PlantVO) data.getSerializableExtra("PlantVO");
                if (vo.getIndex() > -1) {
                    //修改数据
                    adapterZh.remove(vo.getIndex());
                    adapterZh.insert(vo, vo.getIndex());
                } else {
                    // 新增数据
                    adapterZh.add(vo);
                }
                adapterZh.notifyDataSetChanged();
            }

        }
    }

    @Override
    public void del(final int pos) {
        new MaterialDialog.Builder(activity)
                .title("提示")
                .content("是否删除该条种植信息？")
                .positiveText("删除")
                .negativeText("取消")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        delPos = pos;
                        PlantVO vo = (PlantVO) adapterZh.getAllData().get(pos);
                        deletePlant(vo.getPlantInfoId());
                    }
                })
                .show();
    }

    @Override
    public void edit(int pos) {
        PlantVO vo = (PlantVO) adapterZh.getAllData().get(pos);
        vo.setIndex(pos);
        GotoUtil.gotoForResultActivity(activity, AddPlantActivity.class, CODE_ZH, "PlantVO", vo);
    }

    // 获取基本信息
    private void getEnterpriseInfo() {

        HttpParams params = new HttpParams();
        params.put("enterpriseId", AdminXML.getEnterpriseId(activity));
        params.put("resNo", AdminXML.getResNo(activity));

        OkHttpUtil.post(activity, URL.URL_GET_ENTERPRISE_INFO, "数据加载中", params, mHandler,
                MSG_S_0, MSG_F_0);
    }

    //保存信息
    private void saveEnterpriseInfo() {

        if (StringUtil.isTextEmpty(etName)) {
            showToast("请填写企业名称");
            return;
        }

        if (StringUtil.isTextEmpty(etCode)) {
            showToast("请填写统一社会信用代码");
            return;
        }

        if (StringUtil.isTextEmpty(etUser)) {
            showToast("请填写联系人");
            return;
        }

        if (StringUtil.isTextEmpty(etTel)) {
            showToast("请填写手机号");
            return;
        }

        HttpParams params = new HttpParams();
        params.put("enterpriseId", AdminXML.getEnterpriseId(activity));
        params.put("resNo", AdminXML.getResNo(activity));
        params.put("enterpriseName", etName.getText().toString());
        params.put("socialCreditCode", etCode.getText().toString());
        params.put("contactName", etUser.getText().toString());
        params.put("mobilePhone", etTel.getText().toString());

        OkHttpUtil.post(activity, URL.URL_SAVE_ENTERPRISE_INFO, "正在保存", params, mHandler,
                MSG_S_1, MSG_F_1);
    }

    // 删除种植信息
    private void deleteLand(String id) {
        HttpParams params = new HttpParams();
        params.put("enterpriseId", AdminXML.getEnterpriseId(activity));
        params.put("resNo", AdminXML.getResNo(activity));
        params.put("LandParcelID", id);

        OkHttpUtil.post(activity, URL.URL_DELETE_LAND, "正在删除", params, mHandler,
                MSG_S_2, MSG_F_2);
    }

    // 删除种植信息
    private void deletePlant(String id) {
        HttpParams params = new HttpParams();
        params.put("enterpriseId", AdminXML.getEnterpriseId(activity));
        params.put("resNo", AdminXML.getResNo(activity));
        params.put("PlantInfoID", id);

        OkHttpUtil.post(activity, URL.URL_DELETE_PLANT, "正在删除", params, mHandler,
                MSG_S_3, MSG_F_3);
    }

}
